package cc.ufinity.networkdiagnose.manager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.util.StringUtils;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

public class PullTaskParser implements TaskParser {
	
    @Override
    public List<APInfo> parseAPInfo(InputStream is) throws Exception {
        List<APInfo> list = null;
        APInfo info = null;
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "UTF-8");
        int type = parser.getEventType(); 
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
            case XmlPullParser.START_DOCUMENT:
                list = new ArrayList<APInfo>();
                break;
            case XmlPullParser.START_TAG:
                String tag = parser.getName();
                if ("APINFO".equals(tag)) {
                    info = new APInfo();
                } else if ("APName".equals(tag)) {
                    type = parser.next();
                    info.name = parser.getText();
                } else if ("APMac".equals(tag)) {
                    type = parser.next();
                    info.mac = parser.getText();
                }
                break;
            case XmlPullParser.END_TAG:
                tag = parser.getName();
                if ("APINFO".equals(tag)) {
                    list.add(info);
                    info = null;
                }
                break;
            }
            type = parser.next();
        }
        is.close();
        return list;
    }

    @Override
    public List<Task> parse(InputStream is) throws Exception {
    	/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	int j= -1;
    	while ( (j=is.read()) != -1 ) {
    	    baos.write(j);
    	}
    	String content = baos.toString();
    	System.err.println(content);*/
    	
        List<Task> tasks = null;
        List<PingTask> pingTasks = null;
        List<HttpTask> httpTasks = null;
        List<FTPTask> ftpTasks = null;
        Task task = null;
        PingTask pingTask = null;
        HttpTask httpTask = null;
        FTPTask ftpTask = null;
        
        XmlPullParser parser = Xml.newPullParser();
        List<Map<String, String[]>> apList = new ArrayList<Map<String,String[]>>();
        parser.setInput(is, "UTF-8");
        // parser.se
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
            case XmlPullParser.START_DOCUMENT:
                tasks = new ArrayList<Task>();
                break;
            case XmlPullParser.START_TAG:
                String tag = parser.getName(); 
                if(!tag.equals("ApInfo")) { 
                }
                if (tag.equals("Task")) {
                    task = new Task();
                    pingTasks = new ArrayList<PingTask>();
                    httpTasks = new ArrayList<HttpTask>();
                    ftpTasks = new ArrayList<FTPTask>();
                } else if (parser.getName().equals("TaskID")) {
                    type = parser.next();
               	 	apList = new ArrayList<Map<String,String[]>>();
                    task.id = DESManager.getDesString(parser.getText());
                    System.out.print("task.id == " + task.id);
                } else if ("TaskMan".equals(tag)) {
                    type = parser.next();
                    task.taskMan = DESManager.getDesString(parser.getText());
                    //System.out.println("task.taskMan==================== " + task.taskMan);
                } else if ("TaskPhone".equals(tag)) {
                    type = parser.next();
                    task.taskPhone =DESManager.getDesString(parser.getText());
                    //System.out.println("task.taskPhone==================== " + task.taskPhone);
                } else if ("TaskName".equals(tag)) {
                    type = parser.next();
                    task.taskName = DESManager.getDesString(parser.getText());
                    System.out.println("  " + task.taskName);
                } else if ("NetworkType".equals(tag)) {
                    type = parser.next();
                    String tempNetType = DESManager.getDesString(parser.getText());
                    task.netType2 = tempNetType;
                    if(tempNetType!=null && (tempNetType.equals("TD")))
                    	task.selNetType = ConnectivityManager.TYPE_MOBILE_MMS;
                    else if (tempNetType!=null && (tempNetType.equals("GSM"))) {
                    	task.selNetType = ConnectivityManager.TYPE_MOBILE;
					} else {
						task.selNetType = ConnectivityManager.TYPE_WIFI;
					}
                } else if ("APName".equals(tag)) {
                    type = parser.next();
                    task.apName = DESManager.getDesString(parser.getText());
                    //System.out.println("task.apName==================== " + task.apName);
                } else if ("TDGSMCount".equals(tag)) {
                    type = parser.next();
                    try {
                        task.testTaskCount = Integer.parseInt(DESManager.getDesString(parser.getText()));
                        //System.out.println("task.testTaskCount==================== "+task.testTaskCount);
					} catch (Exception e) {
						// TODO: handle exception
					}
                } else if ("MacCount".equals(tag)) {
                    type = parser.next();
                    try {
                        task.testApCount = Integer.parseInt(DESManager.getDesString(parser.getText()));
                        //System.out.println("task.testApCount==================== "+task.testApCount);
					} catch (Exception e) {
						// TODO: handle exception
					}
                } else if ("TaskType".equals(tag)) {
                    type = parser.next();
                    task.taskType = DESManager.getDesString(parser.getText());
                    //System.out.println("task.taskType==================== "+task.taskType);
                }else if ("TestCount".equals(tag)) {
                    type = parser.next();
                    try {
                        task.testAllCount = Integer.parseInt(DESManager.getDesString(parser.getText()));
                        //System.out.println("task.testCount==================== "+task.testCount);
					} catch (Exception e) {
						// TODO: handle exception
						task.testAllCount = 1;
					}
                }else if ("TaskDes".equals(tag)) {
                    type = parser.next();
                    task.taskDes = DESManager.getDesString(parser.getText());
                    //System.out.println("task.taskDes==================== "+task.taskDes);
                } else if ("PingAddress".equals(tag)) {
                    type = parser.next();
                    String pingAddress = DESManager.getDesString(parser.getText());
                    pingTask = task.newPingTask(pingAddress);
                    //System.out.println("pingAddress==================== "+pingAddress);
                } else if ("HttpSite".equals(tag)) {
                    type = parser.next();
                    String httpAddress =DESManager.getDesString( parser.getText());
                    httpTask = task.newHttpTask(httpAddress);
                    //System.out.println("httpAddress==================== "+httpAddress);
                } else if ("FTPAddress".equals(tag)) {
                    type = parser.next();
                    String ftpAddress = DESManager.getDesString(parser.getText());
                    ftpTask = task.newFTPTask(ftpAddress);
                    // task.ftpTasks = parseFTPTask(ftpAddress,task);
                    //System.out.println("ftpAddress==================== "+ftpAddress);
                } else if ("Remark".equals(tag)) {
                    type = parser.next();
                    task.remark =DESManager.getDesString(parser.getText());
                    //System.out.println("task.remark==================== "+task.remark);
                } else if ("ApInfo".equals(tag)) {
	               	 type = parser.next();  
	               	 String t1= parser.getText();
	               	 type = parser.next();  
	               	 
	               	 String tag1 = parser.getName();
	               	 type = parser.next();
	               	 String apName = DESManager.getDesString(parser.getText());
	               	 type = parser.next();  
	               	 type = parser.next();  
	               	 type = parser.next();  
	               	 
 	            	 String tag2 = parser.getName();
 	               	 type = parser.next(); 
 	               	 String apMac =DESManager.getDesString(parser.getText()); 
 	               	 
                     Map<String , String[]> tempMap = new HashMap<String, String[]>();
                     String tempAps[] = new String[2];
                     tempAps[0] = apName;
                     tempAps[1] = "0";
                     tempMap.put(apMac, tempAps);
                     apList.add(tempMap);
                     task.apList = apList;
                }
                break;
            case XmlPullParser.END_TAG:
                tag = parser.getName();
                if ("Task".equals(tag)) {
                    task.ftpTasks = ftpTasks;
                    task.pingTasks = pingTasks;
                    task.httpTasks = httpTasks;
                    task.apList = apList;
                    tasks.add(task);
                    task = null;
                } else if ("PingAddress".equals(tag)) {
                    pingTasks.add(pingTask);
                    pingTask = null;
                } else if ("HttpSite".equals(tag)) {
                    httpTasks.add(httpTask);
                    httpTask = null;
                } else if ("FTPAddress".equals(tag)) {
                    ftpTasks.add(ftpTask);
                    ftpTask = null;
                }
                break;
            }
            type = parser.next();
        }
        is.close();
        
        return tasks;
    }

     
    /**
     * @ XmlFileCreator这个方法是为了建立一个xml格式的文件
     * @ 在里面写入的是在测试过程中的所有的需要上传的属性
     * @ 在每次上传到时候，都会重新的建立一个名字：yyyyMMddHHmmsss精确到毫秒
     */
    
    public String XmlFileCreator(Task task) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        Date curDate = new Date(System.currentTimeMillis());
        String fileName = formatter.format(curDate) + ".xml";
        File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/wlantest/" + fileName);
        Log.d("XmlFileCreator", "新的XML文件：" + newxmlfile.getName());
        try {
            if (!newxmlfile.exists())
                newxmlfile.createNewFile();
        } catch (IOException e) {
            Log.e("XmlFileCreator", "创建XML文件出错：", e);
            return null;
        }
        // we have to bind the new file with a FileOutputStream
        FileOutputStream fileos = null;
        try {
            fileos = new FileOutputStream(newxmlfile);
        } catch (FileNotFoundException e) {
            Log.e("XmlFileCreator", "写入XML文件出错：", e);
            return null;
        }
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(fileos, "UTF-8");
            serializer.startDocument(null, Boolean.valueOf(true));
            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
            DecimalFormat df = new DecimalFormat("#0.000");
            
            serializer.startTag(null, "Root");//大标签《ROOT》
            
            serializer.startTag(null, "TestResultInfo");//子标签《TestResultInfo》
            String taskId = (task.id==null||task.id.equals(""))?task.testPhone:task.id;
            serializer.startTag(null, "TaskID");
            serializer.text(String.valueOf(taskId));
            serializer.endTag(null, "TaskID");
            
            serializer.startTag(null, "NetType");
            serializer.text(task.netType);
            serializer.endTag(null, "NetType");
            
            serializer.startTag(null, "TestPhone");
            serializer.text(task.testPhone);
            serializer.endTag(null, "TestPhone");
            
            serializer.startTag(null, "Mac");
            serializer.text(task.mac);
            serializer.endTag(null, "Mac");
            
            serializer.startTag(null, "Lac");
            serializer.text(task.lac);
            serializer.endTag(null, "Lac");
            
            serializer.startTag(null, "Ci");
            serializer.text(task.ci);
            serializer.endTag(null, "Ci");
            
            serializer.startTag(null, "SiteDescript");
            serializer.text(task.taskAddress);
            serializer.endTag(null, "SiteDescript");
            
            serializer.startTag(null, "StartTime");
            serializer.text(task.startTime);
            serializer.endTag(null, "StartTime");
            
            serializer.startTag(null, "EndTime");
            serializer.text(task.endTime);
            serializer.endTag(null, "EndTime");

            serializer.startTag(null, "Longitute");
            serializer.text(task.gps.Longitute);
            serializer.endTag(null, "Longitute");
            
            serializer.startTag(null, "Latitute");
            serializer.text(task.gps.Latitute);
            serializer.endTag(null, "Latitute");

            serializer.startTag(null, "RelevanceAPAvgTime");
            serializer.text(task.relevanceAPAvgTime);
            serializer.endTag(null, "RelevanceAPAvgTime");
            
            serializer.startTag(null, "RelevanceAPSuccessRate");
            serializer.text(task.relevanceAPSuccessRate);
            serializer.endTag(null, "RelevanceAPSuccessRate");

            serializer.startTag(null, "RSSI");
            serializer.text(task.rssi);
            serializer.endTag(null, "RSSI");

            serializer.startTag(null, "SNR");
            serializer.text("-1");
            serializer.endTag(null, "SNR");

            serializer.startTag(null, "WebDelay");
            serializer.text(task.webDelay);
            serializer.endTag(null, "WebDelay");

            serializer.startTag(null, "WebSuccessRate");
            serializer.text(task.webSuccessRate);
            serializer.endTag(null, "WebSuccessRate");

            serializer.startTag(null, "WebOffSuccessRate");
            serializer.text(task.webOffSuccessRate);
            serializer.endTag(null, "WebOffSuccessRate");

            serializer.startTag(null, "PeapDelay");
            serializer.text("0");
            serializer.endTag(null, "PeapDelay");

            serializer.startTag(null, "PeapOffSuccessRate");
            serializer.text("0");
            serializer.endTag(null, "PeapOffSuccessRate");

           /* serializer.startTag(null, "SimSuccessRate");
            serializer.text("0");
            serializer.endTag(null, "SimSuccessRate");

            serializer.startTag(null, "SimOffSuccessRate");
            serializer.text("0");
            serializer.endTag(null, "SimOffSuccessRate");
*/
            List<HttpTask> httpTasks = task.httpTasks;
            if (httpTasks != null) {
                Iterator<HttpTask> iterHttp = httpTasks.iterator();
                double delays = 0.0;
                // double speeds = 0.0;
                int failedTimes = 0;
                int num = httpTasks.size();
                if(iterHttp != null){
                	while (iterHttp.hasNext()) {
                        HttpTask httpTask = iterHttp.next();
                        httpTask.delay = (httpTask.delay==null||httpTask.delay.equals(""))?"0":httpTask.delay;
                        delays = delays + Double.parseDouble(httpTask.delay);
                        failedTimes += httpTask.failedTimes;
                    }
                }
                int temp = num * task.testCount;
                float successRate = 0;
                if(temp != 0)
                	successRate = ((float) (num * task.testCount - failedTimes) / (num * task.testCount)) * 100;
                serializer.startTag(null, "HttpAnwerDelay");
                double temp2 = 0;
                if(num!=0)
                	temp2 = delays / num;
                serializer.text(String.valueOf(df.format(temp2)));
                serializer.endTag(null, "HttpAnwerDelay");

                serializer.startTag(null, "HttpCallSuccessRate");
                serializer.text(String.valueOf(successRate));
                serializer.endTag(null, "HttpCallSuccessRate");
            } else {
                serializer.startTag(null, "HttpAnwerDelay");
                serializer.text("0");
                serializer.endTag(null, "HttpAnwerDelay");

                serializer.startTag(null, "HttpCallSuccessRate");
                serializer.text("0");
                serializer.endTag(null, "HttpCallSuccessRate");
            }

            List<PingTask> pingTasks = task.pingTasks;
            if (pingTasks != null) {
                Iterator<PingTask> iterPing = pingTasks.iterator();
                float bytes = 0;
                float times = 0;
                float ttls = 0;
                if(iterPing != null){
                	while (iterPing.hasNext()) {
                        PingTask pingTask = iterPing.next();
                        String tempBytes = (pingTask.bytes==null || pingTask.bytes.equals(""))?"0":pingTask.bytes;
                        String tempTime = (pingTask.time==null || pingTask.time.equals(""))?"0":pingTask.time;
                        String tempTtl = (pingTask.ttl==null||pingTask.ttl.equals(""))?"0":pingTask.ttl;
                        bytes = bytes + StringUtils.parseFloat(tempBytes);
                        times = times + StringUtils.parseFloat(tempTime);
                        ttls = ttls + StringUtils.parseFloat(tempTtl);
                    }
                }
                int num = pingTasks.size();

                serializer.startTag(null, "PingAvgDelay");
                serializer.text(String.valueOf(df.format((float) ((float) times / 1000) / num)));
                serializer.endTag(null, "PingAvgDelay");

                serializer.startTag(null, "PingPacketLoss");
                serializer.text("0");
                serializer.endTag(null, "PingPacketLoss");
            } else {
                serializer.startTag(null, "PingAvgDelay");
                serializer.text("0");
                serializer.endTag(null, "PingAvgDelay");

                serializer.startTag(null, "PingPacketLoss");
                serializer.text("0");
                serializer.endTag(null, "PingPacketLoss");
            }

            List<FTPTask> ftpTasks = task.ftpTasks;
            if (ftpTasks != null) {
                Iterator<FTPTask> iterFTP = ftpTasks.iterator();
                double loginTimes = 0.0;
                double upRates = 0.0;
                double downRates = 0.0;
                while (iterFTP.hasNext()) {
                    FTPTask ftpTask = iterFTP.next();
                    loginTimes = loginTimes + ftpTask.loginTime;
                    ftpTask.upRate = (ftpTask.upRate==null || ftpTask.upRate.equals(""))?"0":ftpTask.upRate;
                    ftpTask.downRate = (ftpTask.downRate==null || ftpTask.downRate.equals(""))?"0":ftpTask.downRate;
                    upRates = upRates + Double.parseDouble(ftpTask.upRate);
                    downRates = downRates + Double.parseDouble(ftpTask.downRate);
                }
                int num = ftpTasks.size();
                serializer.startTag(null, "FTPUpSuccessRate");
                serializer.text("100");
                serializer.endTag(null, "FTPUpSuccessRate");

                serializer.startTag(null, "FTPDownSuccessRate");
                serializer.text("100");
                serializer.endTag(null, "FTPDownSuccessRate");

                serializer.startTag(null, "FTPDownAvgSuccessRate");
                if (num!=0) 
                	serializer.text(String.valueOf(df.format(downRates / num)));
                else 
                	serializer.text(String.valueOf(df.format(0)));
                serializer.endTag(null, "FTPDownAvgSuccessRate");
                serializer.startTag(null, "FTPUpAvgSuccessRate");
                if (num!=0)  
                    serializer.text(String.valueOf(df.format(upRates / num))); 
                else 
                    serializer.text(String.valueOf(df.format(0)));
                serializer.endTag(null, "FTPUpAvgSuccessRate");
            } else {
                serializer.startTag(null, "FTPUpSuccessRate");
                serializer.text("0");
                serializer.endTag(null, "FTPUpSuccessRate");

                serializer.startTag(null, "FTPDownSuccessRate");
                serializer.text("0");
                serializer.endTag(null, "FTPDownSuccessRate");

                serializer.startTag(null, "FTPDownAvgSuccessRate");
                serializer.text("0");
                serializer.endTag(null, "FTPDownAvgSuccessRate");

                serializer.startTag(null, "FTPUpAvgSuccessRate");
                serializer.text("0");
                serializer.endTag(null, "FTPUpAvgSuccessRate");
            }

            serializer.startTag(null, "UserIsolateSuccessRate");
            serializer.text(task.userIsolateSuccessRate);
            serializer.endTag(null, "UserIsolateSuccessRate");

            serializer.startTag(null, "UserRoamSuccessRate");
            serializer.text(task.userRoamSuccessRate);
            serializer.endTag(null, "UserRoamSuccessRate");

            serializer.startTag(null, "Time");
            serializer.text("0");
            serializer.endTag(null, "Time");

           

            serializer.endTag(null, "TestResultInfo");
            serializer.endTag(null, "Root");
            serializer.endDocument();
            // write xml data into the FileOutputStream
            serializer.flush();
            // finally we close the file stream
            fileos.close();
        } catch (Exception e) {
            Log.e("XmlFileCreator", "生成XML文件出错：", e);
            return null;
        }
        return fileName;
    }

    
   /**
    * 建立wlan测试的上传文件
    * @param task
    * @return
    */
    public  String CreateWLANxml(Task task,Activity ctx){

    	    LocManager locManager = new LocManager(ctx);
		
		    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsss");
		    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy"+"-"+"MM"+"-"+"dd");
	        Date curDate = new Date(System.currentTimeMillis());
	        String fileName = formatter.format(curDate) + ".xml";
	        
	        //----------------------- begin ----------------------------------------
	        
	        File fileDir1 = ctx.getFilesDir();
	        String path = fileDir1.getParent()+ File.separator + "wlantest" + File.separator;
	        File fileDir2 = new File(path);
	        fileDir2.mkdir();
	        File newxmlfile = new File(path + fileName);
	        
			try {
				if (!newxmlfile.exists()) {
					newxmlfile.createNewFile();
				}
//				System.out.println("+ + + + + + + + 文件路径：" + path);
//				GlobalApp.tree(new File(path), 1);  //查看 XML 文件
			} catch (IOException e) {
				Log.e("CreateWLANxml", "创建XML文件出错：", e);
				return null;
			}
	        
			//----------------------- end ----------------------------------------
          /*
    	    try {
    	    	  File fileDir=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/wlantest/");
   	              fileDir.mkdir();
			} catch (Exception e) {
				// TODO: handle exception
				return null;
			}
	   	    File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/wlantest/"+ fileName);
            Log.d("XmlFileCreator", "新的XML文件：" + newxmlfile.getName());
	        try {           
	             if (!newxmlfile.exists())
	                newxmlfile.createNewFile();
	        } catch (IOException e) {
	            Log.e("XmlFileCreator", "创建XML文件出错：", e);
	            return null;
	        }*/
	        // we have to bind the new file with a FileOutputStream
	        FileOutputStream fileos = null;
	        try {
	            fileos = new FileOutputStream(newxmlfile);
	        } catch (FileNotFoundException e) {
	            Log.e("XmlFileCreator", "写入XML文件出错：", e);
	            return null;
	        }
		
		
		XmlSerializer serializer = Xml.newSerializer(); 
		try {
			serializer.setOutput(fileos, "UTF-8");
			serializer.startDocument(null, Boolean.valueOf(true));
			
			serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
       // start a tag called "root"
       DecimalFormat df = new DecimalFormat("#0.000");
			
	        serializer.startTag("","Root"); 
         // serializer.attribute("","date",formatter1.format(curDate)); 
	      //  serializer.startTag("","graphics");
          serializer.startTag("","TestResultInfo"); 
          
          String taskId = (task.id==null||task.id.equals(""))?task.testPhone:task.id;
          serializer.startTag(null, "TaskID");
          serializer.text(String.valueOf(taskId));
          serializer.endTag(null, "TaskID");
	  	    
	  	   serializer.startTag("","NetType"); 
//	  	   serializer.text(task.netType); 
	  	   serializer.text("WLAN测试"); 
	  	    serializer.endTag("","NetType"); 
	  	    
	  	   serializer.startTag("","TestPhone"); 
	  	    serializer.text(task.testPhone); 
	  	    serializer.endTag("","TestPhone"); 
	  	    
	  	 serializer.startTag("","MAC"); 
	  	    serializer.text(task.scanResult.BSSID); 
	  	    serializer.endTag("","MAC"); 
	  	    
	  	    serializer.startTag("","Lac"); 
	  	    serializer.text(task.lac); 
	  	    serializer.endTag("","Lac"); 
	  	    
	  	 serializer.startTag("","Ci"); 
	  	    serializer.text(task.ci); 
	  	    serializer.endTag("","Ci"); 
	  	    
	  	  serializer.startTag("","SiteDescript"); 
	  	    serializer.text(task.taskAddress); 
	  	    serializer.endTag("","SiteDescript"); 
	  	    
	  	  serializer.startTag("","StartTime"); 
	  	    serializer.text(task.startTime); 
	  	    serializer.endTag("","StartTime"); 
	  	    
	  	  serializer.startTag("","EndTime"); 
	  	    serializer.text(task.endTime); 
	  	    serializer.endTag("","EndTime"); 
	  	
	  	  serializer.startTag("","Longitude"); 
	  	    serializer.text(locManager.longitude); 
	  	    serializer.endTag("","Longitude"); 
	  	    
	  	  serializer.startTag("","Latitude"); 
	  	    serializer.text(locManager.latitude); 
	  	    serializer.endTag("","Latitude"); 
	  	  
	  	    serializer.startTag("","RelevanceAPAvgTime"); 
	  	    serializer.text(task.relevanceAPAvgTime); 
	  	    serializer.endTag("","RelevanceAPAvgTime"); 
	  	    
	  	 serializer.startTag("","RelevanceAPSuccessRate"); 
	  	    serializer.text(task.relevanceAPSuccessRate); 
	  	    serializer.endTag("","RelevanceAPSuccessRate"); 
	  	    
	  	  serializer.startTag("","RSSI"); 
	  	    serializer.text(task.rssi); 
	  	    serializer.endTag("","RSSI"); 
	  	    
	  	  serializer.startTag("","SNR"); 
	  	    serializer.text(task.snr); 
	  	    serializer.endTag("","SNR"); 
	  	
	  	    serializer.startTag("","WebDelay"); 
	  	    serializer.text(task.webDelay); 
	  	    serializer.endTag("","WebDelay"); 
	  	    
	  	 serializer.startTag("","WebSuccessRate"); 
	  	    serializer.text(task.webSuccessRate); 
	  	    serializer.endTag("","WebSuccessRate"); 
	  	    
	  	  serializer.startTag("","WebOffSuccessRate"); 
	  	    serializer.text(task.webOffSuccessRate); 
	  	    serializer.endTag("","WebOffSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapSuccessRate"); 
	  	    serializer.text(task.peapSuccessRate); 
	  	    serializer.endTag("","PeapSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapOffSuccessRate"); 
	  	    serializer.text(task.peapOffSuccessRate); 
	  	    serializer.endTag("","PeapOffSuccessRate"); 
	  	
	  	  /*  serializer.startTag("","SimSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimSuccessRate"); 
	  	    
	  	 serializer.startTag("","SimOffSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimOffSuccessRate"); */
	  	    
	  	    
	  	  List<HttpTask> httpTasks = task.httpTasks;
          if (httpTasks != null) {
              Iterator<HttpTask> iterHttp = httpTasks.iterator();
              double delays = 0.0;
              // double speeds = 0.0;
              int failedTimes = 0;
              int num = httpTasks.size();
              if(iterHttp != null){
            	  while (iterHttp.hasNext()) {
                      HttpTask httpTask = iterHttp.next();
                      httpTask.delay = (httpTask.delay==null || httpTask.delay.equals(""))?"0":httpTask.delay;
                      delays = delays + Double.parseDouble(httpTask.delay);
                      failedTimes += httpTask.failedTimes;
                  }
              }
             
              float successRate = 0;
              if(num* task.testCount != 0)
            	  successRate = ((float) (num * task.testCount - failedTimes) / (num * task.testCount)) * 100;
              serializer.startTag(null, "HttpAnwerDelay");
              if(num != 0 )
            	  serializer.text(String.valueOf(df.format(delays / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text(String.valueOf(successRate));
              serializer.endTag(null, "HttpCallSuccessRate");
          } else {
              serializer.startTag(null, "HttpAnwerDelay");
              serializer.text("0");
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "HttpCallSuccessRate");
          }

          List<PingTask> pingTasks = task.pingTasks;
          if (pingTasks != null) {
              Iterator<PingTask> iterPing = pingTasks.iterator();
              float bytes = 0;
              float times = 0;
              float ttls = 0;
              while (iterPing.hasNext()) {
                  PingTask pingTask = iterPing.next();
                  pingTask.bytes = (pingTask.bytes == null ||pingTask.bytes.equals(""))?"0":pingTask.bytes;
                  pingTask.time = (pingTask.time == null ||pingTask.time.equals(""))?"0":pingTask.time;
                  pingTask.ttl = (pingTask.ttl == null ||pingTask.ttl.equals(""))?"0":pingTask.ttl;
                  bytes = bytes + StringUtils.parseFloat(pingTask.bytes);
                  times = times + StringUtils.parseFloat(pingTask.time);
                  ttls = ttls + StringUtils.parseFloat(pingTask.ttl);
              }
              int num = pingTasks.size();

              serializer.startTag(null, "PingAvgDelay");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format((float) ((float) times / 1000) / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          } else {
              serializer.startTag(null, "PingAvgDelay");
              serializer.text("0");
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          }

          List<FTPTask> ftpTasks = task.ftpTasks;
          if (ftpTasks != null) {
              Iterator<FTPTask> iterFTP = ftpTasks.iterator();
              double loginTimes = 0.0;
              double upRates = 0.0;
              double downRates = 0.0;
              double temp = 0.0;
              int upTimes = ftpTasks.size();
              int downTimes = ftpTasks.size();
              while (iterFTP.hasNext()) {
                  FTPTask ftpTask = iterFTP.next();
                  String updateString =( ftpTask.upRate==null || ftpTask.upRate.equals(""))?"0":ftpTask.upRate;
                  temp = Double.parseDouble(updateString);
                  if(temp <= 0) {
                	  upTimes --;
                  } else {
                	  upRates += temp;
                  }
                  updateString = (ftpTask.downRate==null || ftpTask.downRate.equals(""))?"0":ftpTask.downRate;
                  temp = Double.parseDouble(updateString);
                  if(temp <= 0) {
                	  downTimes --;
                  } else {
                	  downRates += temp;
                  }
                  
                  loginTimes = loginTimes + ftpTask.loginTime;
              }
              int num = ftpTasks.size();
              serializer.startTag(null, "FTPUpSuccessRate");
              if(num!=0) 
            	  serializer.text(String.valueOf(df.format(upTimes / num*100)));
              else 
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpSuccessRate");

              serializer.startTag(null, "FTPDownSuccessRate"); 
              if(num!=0) 
                  serializer.text(String.valueOf(df.format(downTimes / num*100)));
              else 
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              if(num!=0) 
                  serializer.text(String.valueOf(df.format(downRates / num)));
              else 
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              if(num!=0) 
                  serializer.text(String.valueOf(df.format(upRates / num)));
              else 
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          } else {
              serializer.startTag(null, "FTPUpSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpSuccessRate");

              serializer.startTag(null, "FTPDownSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          }
	  	  serializer.startTag("","UserIsolateSuccessRate"); 
	  	    serializer.text(task.userIsolateSuccessRate); 
	  	    serializer.endTag("","UserIsolateSuccessRate"); 
	  	    
	  	  serializer.startTag("","UserRoamSuccessRate"); 
	  	    serializer.text(task.userRoamSuccessRate); 
	  	    serializer.endTag("","UserRoamSuccessRate"); 
	  	    
	  	  serializer.startTag("","Time"); 
	  	    serializer.text(formatter1.format(curDate)); 
	  	    serializer.endTag("","Time"); 
	  	    
	  	  serializer.endTag("","TestResultInfo"); 
	  	    serializer.endTag("","Root"); 
	  	    serializer.endDocument();
	  	   }catch(Exception e){
	  		   e.printStackTrace();
	  	   }
		
		return fileName;
	}
    
    /**
     * 建立GSM测试的上传文件
     * @param task
     * @return
     */
    public String CreateGSMxml(Task task,Activity ctx){
    	
 
    	  LocManager locManager = new LocManager(ctx);
    	  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsss");
          Date curDate = new Date(System.currentTimeMillis());
          String fileName = formatter.format(curDate) + ".xml";
          SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy"+"-"+"MM"+"-"+"dd");
	        //----------------------- begin ----------------------------------------
	        
	        File fileDir1 = ctx.getFilesDir();
	        String path = fileDir1.getParent()+ File.separator + "wlantest" + File.separator;
	        File fileDir2 = new File(path);
	        fileDir2.mkdir();
	        File newxmlfile = new File(path + fileName);
	        
			try {
				if (!newxmlfile.exists()) {
					newxmlfile.createNewFile();
				}
//				System.out.println("+ + + + + + + + 文件路径：" + path);
//				GlobalApp.tree(new File(path), 1);  //查看 XML 文件
			} catch (IOException e) {
				Log.e("CreateWLANxml", "创建XML文件出错：", e);
				return null;
			}
	        
          /*try {
	    	  File fileDir=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/wlantest/");
	              fileDir.mkdir();
			} catch (Exception e) {
				// TODO: handle exception
				return null;
			}
          File newxmlfile = new File(Environment.getExternalStorageDirectory()+ "/wlantest/"+  fileName);
          Log.d("XmlFileCreator", "新的XML文件：" + newxmlfile.getName());
     
	        try {
	            if (!newxmlfile.exists())
	                newxmlfile.createNewFile();
	        } catch (IOException e) {
	            Log.e("XmlFileCreator", "创建XML文件出错：", e);
	        }*/
        FileOutputStream fileos = null;
        try {
            fileos = new FileOutputStream(newxmlfile);
        } catch (FileNotFoundException e) {
            Log.e("XmlFileCreator", "写入XML文件出错：", e);
        }
		
		XmlSerializer serializer = Xml.newSerializer(); 
		try {
	            
			serializer.setOutput(fileos, "UTF-8");
			serializer.startDocument(null, Boolean.valueOf(true));
			
			serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
           DecimalFormat df = new DecimalFormat("#0.000");
			
	      serializer.startTag("","Root"); 
        //  serializer.attribute("","date",formatter1.format(curDate)); 
          serializer.startTag("","TestResultInfo"); 
          String taskId = (task.id==null||task.id.equals(""))?task.testPhone:task.id;
          serializer.startTag(null, "TaskID");
          serializer.text(String.valueOf(taskId));
          serializer.endTag(null, "TaskID");
	  	    
	  	   serializer.startTag("","NetType"); 
	  	   serializer.text("GSM测试"); 
	  	    serializer.endTag("","NetType"); 
	  	    
	  	   serializer.startTag("","TestPhone"); 
	  	    serializer.text(task.testPhone); 
	  	    serializer.endTag("","TestPhone"); 
	  	    
	  	 serializer.startTag("","MAC"); 
//	  	    serializer.text(task.mac); 
	  	 	serializer.text(""); 
	  	    serializer.endTag("","MAC"); 
	  	    
	  	    serializer.startTag("","Lac"); 
	  	    serializer.text(task.lac); 
	  	    serializer.endTag("","Lac"); 
	  	    
	  	 serializer.startTag("","Ci"); 
	  	    serializer.text(task.ci); 
	  	    serializer.endTag("","Ci"); 
	  	    
	  	  serializer.startTag("","SiteDescript"); 
	  	    serializer.text(task.taskAddress); 
	  	    serializer.endTag("","SiteDescript"); 
	  	    
	  	  serializer.startTag("","StartTime"); 
	  	    serializer.text(task.startTime); 
	  	    serializer.endTag("","StartTime"); 
	  	    
	  	  serializer.startTag("","EndTime"); 
	  	    serializer.text(task.endTime); 
	  	    serializer.endTag("","EndTime"); 
	  	
	  	  serializer.startTag("","Longitude"); 
	  	    serializer.text(locManager.longitude); 
	  	    serializer.endTag("","Longitude"); 
	  	    
	  	  serializer.startTag("","Latitude"); 
	  	    serializer.text(locManager.latitude); 
	  	    serializer.endTag("","Latitude"); 
	  	  
	  	    serializer.startTag("","RelevanceAPAvgTime"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","RelevanceAPAvgTime"); 
	  	    
	  	 serializer.startTag("","RelevanceAPSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","RelevanceAPSuccessRate"); 
	  	    
	  	  serializer.startTag("","RSSI"); 
	  	    serializer.text("-"+task.rssi); 
	  	    serializer.endTag("","RSSI"); 
	  	    
	  	  serializer.startTag("","SNR"); 
	  	    serializer.text(task.snr); 
	  	    serializer.endTag("","SNR"); 
	  	
	  	    serializer.startTag("","WebDelay"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebDelay"); 
	  	    
	  	 serializer.startTag("","WebSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebSuccessRate"); 
	  	    
	  	  serializer.startTag("","WebOffSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebOffSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","PeapSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapOffSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","PeapOffSuccessRate"); 
	  	/*
	  	    serializer.startTag("","SimSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimSuccessRate"); 
	  	    
	  	 serializer.startTag("","SimOffSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimOffSuccessRate"); 
	  	    */
	  	    
	  	  List<HttpTask> httpTasks = task.httpTasks;
          if (httpTasks != null) {
              Iterator<HttpTask> iterHttp = httpTasks.iterator();
              double delays = 0.0;
              // double speeds = 0.0;
              int failedTimes = 0;
              int num = httpTasks.size();
              if(iterHttp != null){
            	  while (iterHttp.hasNext()) {
                      HttpTask httpTask = iterHttp.next();
                      httpTask.delay = (httpTask.delay==null || httpTask.delay.equals(""))?"0":httpTask.delay;
                      delays = delays + Double.parseDouble(httpTask.delay);
                      failedTimes += httpTask.failedTimes;
                  }
              }
             
              float successRate = 0;
              if(num *task.testCount != 0)
            	  successRate = ((float) (num * task.testCount - failedTimes) / (num * task.testCount)) * 100;
              serializer.startTag(null, "HttpAnwerDelay");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(delays / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text(String.valueOf(successRate));
              serializer.endTag(null, "HttpCallSuccessRate");
          } else {
              serializer.startTag(null, "HttpAnwerDelay");
              serializer.text("0");
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "HttpCallSuccessRate");
          }

          List<PingTask> pingTasks = task.pingTasks;
          if (pingTasks != null) {
              Iterator<PingTask> iterPing = pingTasks.iterator();
              float bytes = 0;
              float times = 0;
              float ttls = 0;
              if(iterPing != null){
            	  while (iterPing.hasNext()) {
                      PingTask pingTask = iterPing.next();
                      pingTask.bytes = (pingTask.bytes == null ||pingTask.bytes.equals(""))?"0":pingTask.bytes;
                      pingTask.time = (pingTask.time == null ||pingTask.time.equals(""))?"0":pingTask.time;
                      pingTask.ttl = (pingTask.ttl == null ||pingTask.ttl.equals(""))?"0":pingTask.ttl;
                      bytes = bytes + StringUtils.parseFloat(pingTask.bytes);
                      times = times + StringUtils.parseFloat(pingTask.time);
                      ttls = ttls + StringUtils.parseFloat(pingTask.ttl);
                  }
              }
             
              int num = pingTasks.size();

              serializer.startTag(null, "PingAvgDelay");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format((float) ((float) times / 1000) / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          } else {
              serializer.startTag(null, "PingAvgDelay");
              serializer.text("0");
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          }

          List<FTPTask> ftpTasks = task.ftpTasks;
          if (ftpTasks != null) {
              Iterator<FTPTask> iterFTP = ftpTasks.iterator();
              double loginTimes = 0.0;
              double upRates = 0.0;
              double downRates = 0.0;
              double temp = 0.0;
              int upTimes = ftpTasks.size();
              int downTimes = ftpTasks.size();
              if(iterFTP != null){
            	  while (iterFTP.hasNext()) {
                      FTPTask ftpTask = iterFTP.next();
                      String updateString = (ftpTask.upRate==null|| ftpTask.upRate.equals(""))?"0":ftpTask.upRate;
                      temp = Double.parseDouble(updateString);
                      if(temp <= 0) {
                    	  upTimes --;
                      } else {
                    	  upRates += temp;
                      }
                      updateString =( ftpTask.downRate==null||ftpTask.downRate.equals(""))?"0":ftpTask.downRate;
                      temp = Double.parseDouble(updateString);
                      if(temp <= 0) {
                    	  downTimes --;
                      } else {
                    	  downRates += temp;
                      }
                      
                      loginTimes = loginTimes + ftpTask.loginTime;
                  } 
              }
             
              int num = ftpTasks.size();
              serializer.startTag(null, "FTPUpSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(upTimes / num*100)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpSuccessRate");
 
              serializer.startTag(null, "FTPDownSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(downTimes / num*100)));  
              else
                  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(downRates / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(upRates / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          } else {
              serializer.startTag(null, "FTPUpSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpSuccessRate");

              serializer.startTag(null, "FTPDownSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          }
	  	  serializer.startTag("","UserIsolateSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","UserIsolateSuccessRate"); 
	  	    
	  	  serializer.startTag("","UserRoamSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","UserRoamSuccessRate"); 
	  	    
	  	  serializer.startTag("","Time"); 
	  	    serializer.text(formatter1.format(curDate)); 
	  	    serializer.endTag("","Time"); 
	  	    
	  	  serializer.endTag("","TestResultInfo"); 
	  	    serializer.endTag("","Root"); 
	  	    serializer.endDocument();
	  	   }catch(Exception e){
	  		   e.printStackTrace();
	  	   }
	
		return fileName;
	}

    
  /**
   *   建立TD测试的上传文件
   * @param task
   * @return
   */
    public String CreateTDxml(Task task,Activity ctx){

    	   LocManager locManager = new LocManager(ctx);
    	  SimpleDateFormat formatter = new  SimpleDateFormat("yyyyMMddHHmmsss");
		  SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy"+"-"+"MM"+"-"+"dd");
	      Date curDate = new Date(System.currentTimeMillis());
	      
	        String fileName = formatter.format(curDate) + ".xml";
	        
	        //----------------------- begin ----------------------------------------
	        
	        File fileDir1 = ctx.getFilesDir();
	        String path = fileDir1.getParent()+ File.separator + "wlantest" + File.separator;
	        File fileDir2 = new File(path);
	        fileDir2.mkdir();
	        File newxmlfile = new File(path + fileName);
	        
			try {
				if (!newxmlfile.exists()) {
					newxmlfile.createNewFile();
				}
//				System.out.println("+ + + + + + + + 文件路径：" + path);
//				GlobalApp.tree(new File(path), 1);  //查看 XML 文件
			} catch (IOException e) {
				Log.e("CreateWLANxml", "创建XML文件出错：", e);
				return null;
			}
	        
	       /* try {
  	    	  File fileDir=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/wlantest/");
 	              fileDir.mkdir();
			} catch (Exception e) {
				// TODO: handle exception
				return null;
			}
//	        File fileDir=new File(Environment.getExternalStorageDirectory().getAbsolutePath());
//	           fileDir.mkdir();
	        File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/wlantest/"+ fileName);
	        Log.d("XmlFileCreator", "新的XML文件：" + newxmlfile.getName());
	        try {
	            if (!newxmlfile.exists())
	                newxmlfile.createNewFile();
	        } catch (IOException e) {
	            Log.e("XmlFileCreator", "创建XML文件出错：", e);
	        }*/
	        FileOutputStream fileos = null;
	        try {
	            fileos = new FileOutputStream(newxmlfile);
	        } catch (FileNotFoundException e) {
	            Log.e("XmlFileCreator", "写入XML文件出错：", e);
	        }
		
		XmlSerializer serializer = Xml.newSerializer(); 
		try {
			serializer.setOutput(fileos, "UTF-8");
			serializer.startDocument(null, Boolean.valueOf(true));
			
			serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
          DecimalFormat df = new DecimalFormat("#0.000");
			
	        serializer.startTag("","Root"); 
         //serializer.attribute("","date",formatter1.format(curDate)); 
         serializer.startTag("","TestResultInfo"); 
         
         String taskId = (task.id==null||task.id.equals(""))?task.testPhone:task.id;
         serializer.startTag(null, "TaskID");
         serializer.text(String.valueOf(taskId));
         serializer.endTag(null, "TaskID");
	  	    
	  	   serializer.startTag("","NetType"); 
	  	   serializer.text("TD测试"); 
	  	    serializer.endTag("","NetType"); 
	  	    
	  	   serializer.startTag("","TestPhone"); 
	  	    serializer.text(task.testPhone); 
	  	    serializer.endTag("","TestPhone"); 
	  	    
	  	 serializer.startTag("","MAC"); 
//	  	    serializer.text(task.mac); 
	  	 	serializer.text(""); 
	  	    serializer.endTag("","MAC"); 
	  	    
	  	    serializer.startTag("","Lac"); 
	  	    serializer.text(task.lac); 
	  	    serializer.endTag("","Lac"); 
	  	    
	  	 serializer.startTag("","Ci"); 
	  	    serializer.text(task.ci); 
	  	    serializer.endTag("","Ci"); 
	  	    
	  	  serializer.startTag("","SiteDescript"); 
	  	    serializer.text(task.taskAddress); 
	  	    serializer.endTag("","SiteDescript"); 
	  	    
	  	  serializer.startTag("","StartTime"); 
	  	    serializer.text(task.startTime); 
	  	    serializer.endTag("","StartTime"); 
	  	    
	  	  serializer.startTag("","EndTime"); 
	  	    serializer.text(task.endTime); 
	  	    serializer.endTag("","EndTime"); 
	  	
	  	  serializer.startTag("","Longitude"); 
	  	    serializer.text(locManager.longitude); 
	  	    serializer.endTag("","Longitude"); 
	  	    
	  	  serializer.startTag("","Latitude"); 
	  	    serializer.text(locManager.latitude); 
	  	    serializer.endTag("","Latitude"); 
	  	  
	  	    serializer.startTag("","RelevanceAPAvgTime"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","RelevanceAPAvgTime"); 
	  	    
	  	 serializer.startTag("","RelevanceAPSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","RelevanceAPSuccessRate"); 
	  	    
	  	  serializer.startTag("","RSSI"); 
	  	    serializer.text("-"+task.rssi); 
	  	    serializer.endTag("","RSSI"); 
	  	    
	  	  serializer.startTag("","SNR"); 
	  	    serializer.text(task.snr); 
	  	    serializer.endTag("","SNR"); 
	  	
	  	    serializer.startTag("","WebDelay"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebDelay"); 
	  	    
	  	 serializer.startTag("","WebSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebSuccessRate"); 
	  	    
	  	  serializer.startTag("","WebOffSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","WebOffSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","PeapSuccessRate"); 
	  	    
	  	  serializer.startTag("","PeapOffSuccessRate"); 
	  	    serializer.text("-1"); 
	  	    serializer.endTag("","PeapOffSuccessRate"); 
	  	
	  	 /*   serializer.startTag("","SimSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimSuccessRate"); 
	  	    
	  	 serializer.startTag("","SimOffSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","SimOffSuccessRate"); 
	  	    */
	  	    
	  	  List<HttpTask> httpTasks = task.httpTasks;
          if (httpTasks != null) {
              Iterator<HttpTask> iterHttp = httpTasks.iterator();
              double delays = 0.0;
              // double speeds = 0.0;
              int failedTimes = 0;
              int num = httpTasks.size();
              if(iterHttp != null){
            	  while (iterHttp.hasNext()) {
                      HttpTask httpTask = iterHttp.next();
                      httpTask.delay = (httpTask.delay==null || httpTask.delay.equals(""))?"0":httpTask.delay;
                      delays = delays + Double.parseDouble(httpTask.delay);
                      failedTimes += httpTask.failedTimes;
                  }
              }
             
              float successRate = 0;
              if(num *task.testCount != 0)
            	  successRate = ((float) (num * task.testCount - failedTimes) / (num * task.testCount)) * 100;
              serializer.startTag(null, "HttpAnwerDelay");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(delays / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text(String.valueOf(successRate));
              serializer.endTag(null, "HttpCallSuccessRate");
          } else {
              serializer.startTag(null, "HttpAnwerDelay");
              serializer.text("0");
              serializer.endTag(null, "HttpAnwerDelay");

              serializer.startTag(null, "HttpCallSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "HttpCallSuccessRate");
          }

          List<PingTask> pingTasks = task.pingTasks;
          if (pingTasks != null) {
              Iterator<PingTask> iterPing = pingTasks.iterator();
              float bytes = 0;
              float times = 0;
              float ttls = 0;
              if(iterPing != null){
            	  while (iterPing.hasNext()) {
                      PingTask pingTask = iterPing.next();
                      pingTask.bytes = (pingTask.bytes == null ||pingTask.bytes.equals(""))?"0":pingTask.bytes;
                      pingTask.time = (pingTask.time == null ||pingTask.time.equals(""))?"0":pingTask.time;
                      pingTask.ttl = (pingTask.ttl == null ||pingTask.ttl.equals(""))?"0":pingTask.ttl;
                      bytes = bytes + StringUtils.parseFloat(pingTask.bytes);
                      times = times + StringUtils.parseFloat(pingTask.time);
                      ttls = ttls + StringUtils.parseFloat(pingTask.ttl);
                  }
              }
             
              int num = pingTasks.size();

              serializer.startTag(null, "PingAvgDelay");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format((float) ((float) times / 1000) / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          } else {
              serializer.startTag(null, "PingAvgDelay");
              serializer.text("0");
              serializer.endTag(null, "PingAvgDelay");

              serializer.startTag(null, "PingPacketLoss");
              serializer.text("0");
              serializer.endTag(null, "PingPacketLoss");
          }

          List<FTPTask> ftpTasks = task.ftpTasks;
          if (ftpTasks != null) {
              Iterator<FTPTask> iterFTP = ftpTasks.iterator();
              double loginTimes = 0.0;
              double upRates = 0.0;
              double downRates = 0.0;
              double temp = 0.0;
              int upTimes = ftpTasks.size();
              int downTimes = ftpTasks.size();
              if(iterFTP != null){
            	  while (iterFTP.hasNext()) {
                      FTPTask ftpTask = iterFTP.next();
                      String updateString = (ftpTask.upRate==null||ftpTask.upRate.equals(""))?"0":ftpTask.upRate;
                      temp = Double.parseDouble(updateString);
                      if(temp <= 0) {
                    	  upTimes --;
                      } else {
                    	  upRates += temp;
                      }
                      updateString =( ftpTask.downRate==null||ftpTask.downRate.equals(""))?"0":ftpTask.downRate;
                      temp = Double.parseDouble(updateString);
                      if(temp <= 0) {
                    	  downTimes --;
                      } else {
                    	  downRates += temp;
                      }
                      
                      loginTimes = loginTimes + ftpTask.loginTime;
                  } 
              }
             
              int num = ftpTasks.size();
              serializer.startTag(null, "FTPUpSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(upTimes / num*100)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpSuccessRate");
 
              serializer.startTag(null, "FTPDownSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(downTimes / num*100)));  
              else
                  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(downRates / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              if(num != 0)
            	  serializer.text(String.valueOf(df.format(upRates / num)));
              else
            	  serializer.text(String.valueOf(df.format(0)));
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          } else {
              serializer.startTag(null, "FTPUpSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpSuccessRate");

              serializer.startTag(null, "FTPDownSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownSuccessRate");

              serializer.startTag(null, "FTPDownAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPDownAvgSuccessRate");

              serializer.startTag(null, "FTPUpAvgSuccessRate");
              serializer.text("0");
              serializer.endTag(null, "FTPUpAvgSuccessRate");
          }
	  	  serializer.startTag("","UserIsolateSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","UserIsolateSuccessRate"); 
	  	    
	  	  serializer.startTag("","UserRoamSuccessRate"); 
	  	    serializer.text("0"); 
	  	    serializer.endTag("","UserRoamSuccessRate"); 
	  	    
	  	  serializer.startTag("","Time"); 
	  	    serializer.text(formatter1.format(curDate)); 
	  	    serializer.endTag("","Time"); 
	  	    
	  	  serializer.endTag("","TestResultInfo"); 
	  	    serializer.endTag("","Root"); 
	  	    serializer.endDocument();
	  	   }catch(Exception e){
	  		   e.printStackTrace();
	  	   }
	
		return fileName;
	}
    
    @Deprecated
    public final List<PingTask> parsePingTask(String input, Task t) {
        List<PingTask> tasks = new ArrayList<PingTask>();
        if (!StringUtils.isEmpty(input)) {
            String[] s = input.split(";");
            PingTask task = null;
            if (s.length > 0) {
                for (String e : s) {
                    task = t.newPingTask(e);
                    tasks.add(task);
                }
            } else {
                tasks.add(t.newPingTask(input));
            }
        }
        return tasks;
    }

    @Deprecated
    public final List<HttpTask> parseHttpTask(String input, Task t) {
        List<HttpTask> tasks = new ArrayList<HttpTask>();
        if (!StringUtils.isEmpty(input)) {
            String[] s = input.split(";");
            HttpTask task = null;
            if (s.length > 0) {
                for (String e : s) {
                    task = t.newHttpTask(e);
                    tasks.add(task);
                }
            } else {
                tasks.add(t.newHttpTask(input));
            }
        }
        return tasks;
    }

    @Deprecated
    public final List<FTPTask> parseFTPTask(String input, Task t) {
        List<FTPTask> tasks = new ArrayList<FTPTask>();
        if (!StringUtils.isEmpty(input)) { 
            String[] s = input.split(";");
            FTPTask task = null;
            if (s.length > 0) {
                for (String e : s) {
                    task = t.newFTPTask(e);
                    tasks.add(task);
                }
            } else {
                tasks.add(t.newFTPTask(input));
            }
        }
        return tasks;
    }
}
